package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.server.interceptor.UserHolder;
import com.itheima.tanhua.dubbo.api.RecommendUserApi;
import com.itheima.tanhua.dubbo.api.UserInfoApi;
import com.itheima.tanhua.model.domain.PageResult;
import com.itheima.tanhua.model.domain.UserInfo;
import com.itheima.tanhua.model.dto.RecommendUserDto;
import com.itheima.tanhua.model.mongo.RecommendUser;
import com.itheima.tanhua.model.mongo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 今日佳人
     *
     * @return
     */
    public TodayBest todayBest() {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //查找今日佳人id
        RecommendUser recommendUser = recommendUserApi.findWithMaxScore(userId);

        //如果数据为空，设置默今日佳人
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99d);
        }
        //查找今日佳人信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);

        return todayBest;
    }

    /**
     * 分页查询推荐列表
     *
     * @param recommendUserDto
     * @return
     */
    public PageResult recommendation(RecommendUserDto recommendUserDto) {

        //获取用户id
        Long toUserId = UserHolder.getUserId();
        //查询推荐分页好友的id
        PageResult pageResult = recommendUserApi.findUserByPage(recommendUserDto.getPage(), recommendUserDto.getPagesize(), toUserId);
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();
        //再根据推荐好友id查询用户详细信息
        //从items中取出对象的userid存放到集合中
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //过滤条件
        UserInfo user = new UserInfo();
        user.setAge(recommendUserDto.getAge());
        user.setGender(recommendUserDto.getGender());
        //查询过滤条件后的推荐用户信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, user);
        //返回
        List<TodayBest> list = new ArrayList<>();

        //构造返回值
        for (RecommendUser item : items) {
            UserInfo userInfo = userInfoMap.get(item.getUserId());

            TodayBest todayBest = TodayBest.init(userInfo, item);
            list.add(todayBest);
        }

        pageResult.setItems(list);

        return pageResult;
    }
}
